import { VNodeDirective } from '@/interface/types/vnode';

type IRippleElement = EventTarget & HTMLElement;

interface IRippleTarget extends IRippleElement {
  _ripple: any;
}

interface IRippleConfig {
  center?: boolean;
  class?: string;
  circle?: boolean;
}

/* 水波纹出现 */
const rippleShow = (e: MouseEvent) => {
  e.stopPropagation();
  const value: IRippleConfig = {};
  const element: IRippleTarget = e.currentTarget as IRippleTarget;
  updateRipple(element, {});
  // 如果当前的e[rippleStop]为true说明上一次水波纹还没有结束
  if (!element || !element._ripple || element._ripple.touched) return;

  value.center = element._ripple.centered;

  if (element._ripple.class) {
    value.class = element._ripple.class;
  }

  ripples.show(e, element, value);
}

/* 水波纹离开 */
const rippleHide = (e: MouseEvent) => {
  const element: IRippleTarget = e.currentTarget as IRippleTarget;
  if (!element || !element._ripple) return;

  // 鼠标事件的话 只有这一句话有用
  ripples.hide(element)
}

function updateRipple(el: IRippleTarget, value: IRippleConfig) {
  // 配置
  el._ripple = el._ripple || {};
  // 有效性
  el._ripple.enabled = true; // 先给一个true
  // 传过来的值, 一般情况下都是{}
  value = value || {};
  // 是否居中
  if (value.center) {
    el._ripple.centered = true;
  }
  // 自定义样式类
  if (value.class) {
    el._ripple.class = value.class;
  }
  // 是否为圆
  if (value.circle) {
    el._ripple.circle = value.circle;
  }
}

const transform = (el: HTMLElement, value: string) => el.style.transform = value;

const opacity = (el: HTMLElement, value: string | number) => el.style.opacity = value.toString();

const calculate = (e: MouseEvent, el: IRippleTarget, value: IRippleConfig = {}) => {
  let localX = 0
  let localY = 0

  // 获取当前元素的left和top
  const offset = el.getBoundingClientRect()
  // 如果不是触摸事件, 当前的e就是target
  const target = e

  localX = target.clientX - offset.left
  localY = target.clientY - offset.top

  let radius = 0
  let scale = 0.3
  if (el._ripple && el._ripple.circle) {
    scale = 0.15;
    radius = el.clientWidth / 2;
    radius = value.center ? radius : radius + Math.sqrt((localX - radius) ** 2 + (localY - radius) ** 2) / 4;
  } else {
    radius = Math.sqrt(el.clientWidth ** 2 + el.clientHeight ** 2) / 2;
  }

  const centerX = `${(el.clientWidth - (radius * 2)) / 2}px`
  const centerY = `${(el.clientHeight - (radius * 2)) / 2}px`

  const x = value.center ? centerX : `${localX - radius}px`
  const y = value.center ? centerY : `${localY - radius}px`

  return {
    radius,
    scale,
    x,
    y,
    centerX,
    centerY
  }
}



const ripples = {
  /* eslint-disable max-statements */
  show(e: MouseEvent, el: IRippleTarget, value: IRippleConfig = {}) {
    // 没有配置, 或者配置不可用
    if (!el._ripple || !el._ripple.enabled) return;

    const container = document.createElement('span');
    const animation = document.createElement('span');

    container.appendChild(animation);

    // 给容器的类名赋值
    container.className = 'v-ripple__container';

    // 给容器添加外部类名, 如果有的话
    if (value.class) {
      container.className += ` ${value.class}`;
    }

    // { radius, scale, x, y, centerX, centerY }
    const {
      radius,
      scale,
      x,
      y,
      centerX,
      centerY
    } = calculate(e, el, value)

    const size = `${radius * 2}px`;
    animation.className = 'v-ripple__animation';
    animation.style.width = size;
    animation.style.height = size;

    el.appendChild(container);

    const computed = window.getComputedStyle(el);

    // 给el设置position(el就是当前触发点击的元素)
    if (computed && computed.position === 'static') {
      el.style.position = 'relative';
      el.dataset.previousPosition = 'static';
    }
    // 给animation元素添加类
    animation.classList.add('v-ripple__animation--enter');
    animation.classList.add('v-ripple__animation--visible');

    // 给animation添加动画属性
    transform(animation, `translate(${x}, ${y}) scale3d(${scale},${scale},${scale})`);
    opacity(animation, 0);

    // 给animation设置active时间戳(性能时间戳)
    animation.dataset.activated = String(performance.now());

    setTimeout(() => {
      animation.classList.remove('v-ripple__animation--enter');
      animation.classList.add('v-ripple__animation--in');
      transform(animation, `translate(${centerX}, ${centerY}) scale3d(1,1,1)`);
      opacity(animation, 0.25);
    }, 0)
  },

  hide(el: IRippleTarget) {
    if (!el || !el._ripple || !el._ripple.enabled) return;

    const ripples: Array<HTMLElement> = el.getElementsByClassName('v-ripple__animation') as any as Array<HTMLElement>;

    if (ripples.length === 0) return;
    const animation = ripples[ripples.length - 1];

    if (animation.dataset.isHiding) return;
    else animation.dataset.isHiding = 'true';

    const diff = performance.now() - Number(animation.dataset.activated);
    const delay = Math.max(250 - diff, 0);

    setTimeout(() => {
      animation.classList.remove('v-ripple__animation--in');
      animation.classList.add('v-ripple__animation--out');
      opacity(animation, 0);

      setTimeout(() => {
        const ripples = el.getElementsByClassName('v-ripple__animation');
        if (ripples.length === 1 && el.dataset.previousPosition) {
          el.style.position = el.dataset.previousPosition;
          delete el.dataset.previousPosition;
        }

        animation.parentNode && el.removeChild(animation.parentNode);
      }, 300)
    }, delay)
  },
}

const beforeMount = (el: HTMLElement, binding: VNodeDirective) => {
  // 如果没有传值, 或者传的值为true则绑定事件
  if (typeof binding.value === 'undefined' || binding.value) {          
    el.addEventListener('mousedown', rippleShow);
    el.addEventListener('mouseup', rippleHide);
    el.addEventListener('mouseleave', rippleHide);
  } else {
    beforeUnmount(el, binding);
  }
}
const beforeUnmount = (el: HTMLElement, binding?: VNodeDirective) => {
  el.removeEventListener('mousedown', rippleShow);
  el.removeEventListener('mouseup', rippleHide);
  el.removeEventListener('mouseleave', rippleHide);
}

export const Ripple = {
  beforeMount,
  beforeUnmount
}